import React, { useCallback, useEffect, useState } from 'react';
import { Input, Table, Tree, Empty } from 'antd';
import type { DirectoryTreeProps } from 'antd/lib/tree';
import { CloseCircleFilled } from '@ant-design/icons';
import { TextWidget } from '@inbiz/react';
import { useApp } from '@inbiz/render';
// import { toJS } from '@formily/reactive';
import Pagination from '../SyncComponents/Pagination';
import { InbizIcon } from '@inbiz/utils';
import { cloneDeep } from 'lodash';
import useDebounce from './components/hook';
import styles from './index.less';
const { DirectoryTree } = Tree;

let allSelect = new Map();

const TreeAndTable = (props: any) => {
  const { showTagList } = props;
  const appInfo = useApp();
  // 当前选中分组
  const [activeGroup, $activeGroup] = useState(props.defaultTreeSelectKey);
  // 选择数据Outid
  const [selecteds, $selecteds] = useState<any[]>(props.selectKey);
  // 选择数据详情
  const [selectedInfos, $selectedInfos] = useState<any[]>(props.selectInfo);
  // 页面列表数据
  let [dataSource, $dataSource] = useState<any[]>([]);
  // 筛选后的列表数据
  let [filterDataSource, $filterDataSource] = useState<any[]>([]);
  // 页面列表加载
  const [pageLoading, $pageLoading] = useState<boolean>(false);
  // 当前页码
  const [current, $current] = useState<number>(1);
  // 当前分页数值
  const [pageSize, $pageSize] = useState<number>(10);
  // 页面总数
  const [pageTotal, $pageTotal] = useState<number>(0);
  // 搜索值
  const [searchIpts, $searchIpts] = useState<string>('');
  // 防抖后的搜索值
  const searchTxt = useDebounce(searchIpts, 500);

  // 选中组
  const clickGroup = (id: any) => {
    $activeGroup(id);
  };

  // 筛选搜索值更新
  const searchChange = async (e: any) => {
    $searchIpts(e.target.value);
  };

  // 搜索值变化防抖后查列表数据
  useEffect(() => {
    $current(1);
    getMessgeGroup([activeGroup], searchTxt, 1);
  }, [searchTxt]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    $selecteds(newSelectedRowKeys)
    // 通过选中key求当前应用table数据的交集
    const data = dataSource.filter((item) =>
      newSelectedRowKeys.some((item2) => item.TableKey == item2),
    );

    let group = [];
    let group2 = [];
    if (activeGroup == 'other') {
      group = [];
      group2 = [];
      [...allSelect.keys()].forEach((key) => {
        group = data.filter((item) => item.TableKey == key);
        group2 = allSelect
          .get(key)
          .filter((oldValue: any) =>
            dataSource.every((newValue) => oldValue.TableKey != newValue.TableKey),
          );
        allSelect.set(key, group.concat(group2));
      });
    }

    // 根据应用维护选中Map
    allSelect.set(activeGroup, data);
    let newSelect: any[] = [];

    // 给上级列表转成的是一个综合数组
    [...allSelect.values()].forEach((item) => {
      newSelect = newSelect.concat(item);
    });

    let list: any[] = [];
    $filterDataSource((pre: any[]) => {
      pre.forEach((item: any) => {
        list.push(item);
      });
      return pre;
    });

    $selectedInfos((pre: any[]) => {
      let arr: any[] = [];
      // pre.forEach((item: any) => {
      //   let record = toJS(item);
      //   let fil = list.some((val: any) => val.TableKey === record.TableKey);
      //   if (!fil) {
      //     arr.push(record);
      //   }
      // });
      let all: any[] = [...arr];
      newSelect.forEach((item: any) => {
        let fil = all.some((val: any) => val.TableKey === item.TableKey);
        if (!fil) all.push(item);
      });
      props.setSelectGroup && props.setSelectGroup(all);
      return all;
    });
  };

  // 删除单项
  const delItem = (id: string) => {
    $selecteds((pre: any[]) => {
      let arr = pre.filter((item: string) => item !== id);
      return arr;
    });
    $selectedInfos((pre: any[]) => {
      let arr = pre.filter((item: any) => item.TableKey !== id);
      props.setSelectGroup && props.setSelectGroup(arr);
      return arr;
    });
  };

  const onSelect: DirectoryTreeProps['onSelect'] = async (keys, info) => {
    clickGroup(keys[0]);
    $current(1);
    if (props.onTreeSelect) {
      if (searchTxt !== '') {
        $searchIpts('');
        return;
      }
      $pageLoading(true);
      const data = await props.onTreeSelect({
        key: cloneDeep(keys),
        searchText: searchTxt,
        pageIndex: 1,
        pageSize: pageSize,
      });
      $pageTotal(data?.TotalCount || 0);
      $dataSource(props.getTableList(data?.Items, appInfo.AppId) || []);
      $filterDataSource(data?.Items || []);
      $pageLoading(false);
    }
  };

  // 分页组件变化
  const pageOnchange = async (e: any) => {
    $pageLoading(true);
    $current(e.current);
    $pageSize(e.pageSize);
    const data = await props.onTreeSelect({
      key: [activeGroup],
      searchText: searchTxt,
      pageIndex: e.current,
      pageSize: e.pageSize,
    });
    $dataSource(props.getTableList(data?.Items, appInfo.AppId));
    $filterDataSource(data.Items);
    $pageLoading(false);
  };

  const getMessgeGroup = async (
    key: any,
    searchTxt = '',
    pageIndex?: number,
  ) => {
    $pageLoading(true);
    const data = await props.onTreeSelect({
      key: cloneDeep(key),
      searchText: searchTxt,
      pageIndex: pageIndex ? pageIndex : current,
      pageSize: pageSize,
    });
    $pageTotal(data.TotalCount);
    $dataSource(props.getTableList(data?.Items, appInfo.AppId));
    $filterDataSource(data.Items);
    $pageLoading(false);
  };

  useEffect(() => {
    //应用选中数据恢复
    let allOther: any = [];
    props.treeData.forEach((item: any) => {
      const nowAppData = props.selectGroup.filter(
        (group: any) => item.key == group.AppId,
      );
      allSelect.set(item.key, nowAppData);
      if (item.children) {
        item.children.forEach((item2: any) => {
          const nowAppData2 = props.selectGroup.filter(
            (group2: any) => item2.key == group2.AppId,
          );
          allOther = allOther.concat(nowAppData2);
          allSelect.set(item2.key, nowAppData2);
        });
      }
    });
    $selecteds(props.selectKey);
  }, [props.selectGroup, props.selectKey]);

  return (
    <div className={styles['inbiz-component-TreeAndTable-picker']}>
      <div
        className={styles['content']}
        style={{ height: showTagList ? 377 : 477 }}
      >
        <div className={styles['left-tree']}>
          <DirectoryTree
            icon={<></>}
            defaultSelectedKeys={[activeGroup]}
            switcherIcon={
              <InbizIcon
                type={'icon-ic-show_more'}
                style={{
                  fontSize: 14,
                  position: 'relative',
                  color: '#aaa',
                  top: '1px',
                  right: '-2px',
                }}
              />
            }
            onSelect={onSelect}
            defaultExpandAll
            treeData={props.treeData}
          />
        </div>
        <div className={styles['right-nav']}>
          <div className={styles['right-title']}>
            <Input
              value={searchIpts}
              onChange={searchChange}
              placeholder={props.inputPlaceholder}
              suffix={
                <InbizIcon type="icon-ic-sousuo" style={{ color: '#999' }} />
              }
            />
          </div>
          <div className={styles['page-list']}>
            <Table
              columns={props.tableColumns}
              dataSource={props.getTableList(filterDataSource, appInfo.AppId)}
              loading={pageLoading}
              size="small"
              scroll={{ y: showTagList ? 250 : 350 }}
              rowKey={'TableKey'}
              rowSelection={{
                selectedRowKeys: selecteds,
                defaultSelectedRowKeys: selecteds,
                onChange: onSelectChange,
              }}
              onRow={(record) => {
                return {
                  onClick: (event) => {
                    let val = record['TableKey'];
                    let rowKeys: any = [];
                    selecteds.forEach((x) => {
                      rowKeys.push(x);
                    });
                    let idx = rowKeys.indexOf(val);
                    if (idx === -1) {
                      rowKeys.push(val);
                    } else {
                      rowKeys.splice(idx, 1);
                    }
                    onSelectChange(rowKeys);
                  }, // 点击行
                };
              }}
              pagination={false}
              locale={{
                emptyText: (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description={<TextWidget>TreeAndTable.empty_text</TextWidget>}
                  />
                ),
              }}
            />
          </div>
          <Pagination
            size="small"
            options={[10, 20, 30, 40, 50]}
            total={pageTotal}
            current={current}
            pageSize={pageSize}
            onChange={pageOnchange}
          />
        </div>
      </div>
      {showTagList && (
        <div className={styles['checked-list']}>
          {selectedInfos.map((item: any) => {
            return (
              <div className={styles['checked-item']} key={JSON.stringify(item)}>
                <span>{item.Name}</span>
                <CloseCircleFilled onClick={() => delItem(item.TableKey)} />
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default TreeAndTable;
